/*
 * @Author: huyu
 * @Date: 2020-06-06 11:25:34
 * @Last Modified by: huyu
 * @Last Modified time: 2020-06-21 00:11:47
 */

// 博客首页
import React from "react"
import BlogList from "../../components/BlogList"
import LayoutBlog from "../../components/layoutBlog"
import SEO from "../../components/SEO"
import style from "./index.module.less"

export default class Home extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      // 搜索关键字
      keyword: "",
    }
  }

  // 搜索框值变化
  onChangeInput = e => {
    this.setState({ keyword: e.target.value })
  }

  // 情况搜索
  onClickClear = () => {
    this.setState({ keyword: "" })
  }

  render() {
    const { keyword } = this.state
    const {
      data: { allMarkdownRemark = { edges: [] } },
    } = this.props
    let filterEdges = allMarkdownRemark.edges.filter(d => {
      if (keyword) {
        if (d.node) {
          // 搜索支持搜索标题、标签和摘要
          if (
            d.node.frontmatter.title.indexOf(keyword) !== -1 ||
            d.node.frontmatter.tag.indexOf(keyword) !== -1 ||
            d.node.excerpt.indexOf(keyword) !== -1
          ) {
            return true
          }
        }
        return false
      }
      return true
    })
    return (
      <LayoutBlog showNav>
        <SEO title="文章列表" />
        <div className={style.main}>
          <p className={style.searchBar}>
            <span className={style.searchInput}>
              <input
                placeholder="请输入关键字"
                value={keyword}
                onChange={this.onChangeInput}
                maxLength={26}
              />
              {keyword.length > 0 && (
                <button
                  title="清空搜索"
                  className={style.clear}
                  onClick={this.onClickClear}
                >
                  +
                </button>
              )}
            </span>
            <span className={style.ext}>共{filterEdges.length || 0}篇文章</span>
          </p>
          <BlogList>
            {filterEdges.map(d => (
              <BlogList.Item key={d.node.id} data={d.node} keyword={keyword} />
            ))}
          </BlogList>
        </div>
      </LayoutBlog>
    )
  }
}

export const query = graphql`
  query {
    allMarkdownRemark(
      sort: { fields: [frontmatter___date], order: DESC }
      limit: 1000
    ) {
      totalCount
      edges {
        node {
          id
          frontmatter {
            title
            date
            tag
          }
          excerpt
          fields {
            slug
          }
        }
      }
    }
  }
`
